<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="constants.StringConstants" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Plan of Menu Configuration</title>
<link href="css/mystyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<span style="float:left"><a href="/XMLProject/admin/admin-home.jsp">Go to Home</a></span><br/>
	<span style="float:right">
		Hi, <strong>${sessionScope.ADMIN_USERNAME}</strong>-
		<a href="AccountServlet?action=<%=StringConstants.LOGOUT%>">Logout</a>
	</span>
	<center><h2>Plan Configuration</h2>
	<c:set var="menuId" value="${requestScope.MENUID}"></c:set>
	<c:set var="numberOfDays" value="${requestScope.NUMBEROFDAYS}"></c:set>
	<c:set var="numberOfMealsPerDay" value="${requestScope.NUMBERMEALSPERDAY}"></c:set>
	Days 
	<select id="cbDay" name="cbDay">
  		<c:forEach var="i" begin="1" end="${numberOfDays}">
  			<option value="${i}">${i}</option>
  		</c:forEach>
	</select>
	
	<c:forEach var="d" begin="1" end="${numberOfDays}">
		<c:forEach var="m" begin="1" end="${numberOfMealsPerDay}">
			<c:set var="mealOrder" value="${(d-1)*numberOfMealsPerDay + m}"></c:set>
			<div id="meals-${mealOrder}" class="nodisplay-meal-div">
				<h3><strong>Meal No.${m}</strong></h3>
				<a href="#" onclick="load_pick_dish('<%= StringConstants.LOAD_DISHES_IN_MEALS %>', ${menuId}, ${mealOrder}, ${d})">Edit Dishes</a>
				<input type="hidden" id="dish-list-${mealOrder}" value="" />
				<div id="meals-content-${(d-1)*numberOfMealsPerDay + m}">
				</div>
			</div>
		</c:forEach>
	</c:forEach>
	</center>
</body>

<script type="text/javascript">
	var loaded_days = [];
	var out_of_date = [];
	
	document.getElementById("cbDay").onchange = function () {
		var day = document.getElementById("cbDay").value;
		load_days(parseInt(day), parseInt(day) + 2);
		
		var numberOfMealsPerDay = '${numberOfMealsPerDay}';
		var fromMeal = (day-1) * numberOfMealsPerDay + 1;
		var toMeal = fromMeal + parseInt(numberOfMealsPerDay) -1;
		
		var meal_div_list = document.getElementsByClassName("display-meal-div");
		for (var i = 0; i < parseInt(numberOfMealsPerDay); i++) {
			meal_div_list[0].className = 'nodisplay-meal-div';
		}

		for (var i = fromMeal; i <= toMeal; i++) {
			var meal_div = document.getElementById("meals-" + i);
			meal_div.className = 'display-meal-div';
		}
	};
	
	function load_days(fromDay, toDay) {
		// check loaded days and out of date
		for (var need_day = fromDay; need_day <= toDay; need_day++) {
			for (var i in loaded_days) {
				if (need_day == loaded_days[i] && out_of_date[loaded_days[i]] != true) {
					if (fromDay == loaded_days[i]) {
						return load_days(fromDay+1, toDay);
					} else if (fromDay < loaded_days[i]) {
						return load_days(fromDay, loaded_days[i] - 1);
					}
				}
			}
		}
		var menuId = '${requestScope.MENUID}';
		var xmlhttp;
		if (window.XMLHttpRequest) {
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else {
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var root = xmlhttp.responseXML;
				var xpathExp = "//PlanInMeal";
				var planInMealList = root.evaluate(xpathExp, root, null, XPathResult.ANY_TYPE,null);
				
				var menuId;
				var mealOrder;
				var dishId;
				var dishName;
				var dishImage;
				var planInMeal = planInMealList.iterateNext();
				while (planInMeal) {
					  menuId = planInMeal.getElementsByTagName("menuId")[0].firstChild.nodeValue;;
					  mealOrder = planInMeal.getElementsByTagName("mealOrder")[0].firstChild.nodeValue;;
					  
					  xpathExp = "//PlanInMeal[menuId='" + menuId + "' and mealOrder='" + mealOrder + "']/dishList/Dish";
					  var dishList = root.evaluate(xpathExp, root, null, XPathResult.ANY_TYPE, null);
					  var dish = dishList.iterateNext();
					  
				      // generate div content and dish list hidden field
					  var meal_content_div = document.getElementById("meals-content-" + mealOrder);
					  meal_content_div.innerHTML = '';
				      var dish_list_hidden = document.getElementById("dish-list-" + mealOrder);
				      dish_list_hidden.value = '';
					  while (dish) {
						  dishId = dish.getAttribute["id"];
						  dishName = dish.getElementsByTagName("name")[0].firstChild.nodeValue;
						  if (dish.getElementsByTagName("imgPath")[0].firstChild != null) {
							  dishImage = dish.getElementsByTagName("imgPath")[0].firstChild.nodeValue;
						  } else {
							  dishImage = '';
						  }
						  
						  meal_content_div.innerHTML += 'Dish Name: ' + dishName + '<br/><img src="' + dishImage + '" width="50px" height="50px"/><br/>'; 
						  dish_list_hidden.value += dishId + ',';
						  
						  dish = dishList.iterateNext();
					  }
					  dish_list_hidden.value = dish_list_hidden.value.substring(0, dish_list_hidden.value.length -1);
					  
					  planInMeal = planInMealList.iterateNext();
				}
				// set loaded_days and out_of_date
				for (var i = fromDay; i <= toDay; i++) {
					loaded_days.push(i);
					out_of_date[i] = false;
					setTimeout(function() { out_of_date[i] = true; }, 300000);
				}
			}
		}
		xmlhttp.open("POST", "PlanServlet", true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlhttp.send('action=load-meals-in-days&menuId='+ menuId + '&fromDay=' + fromDay + '&toDay=' + toDay);
	}
	
	function load_pick_dish(action, menuId, mealOrder, day) {
		var popup = window.open("PlanServlet?action=" + action + "&menuId=" + menuId + "&mealOrder=" + mealOrder,
				"_blank","toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=200, width=500, height=500");
		popup.onbeforeunload = function () {
			var day_int = parseInt(day);
			out_of_date[day_int] = true;
			load_days(day_int, day_int);
		}
	}
	
	var readyStateCheckInterval = setInterval(function() {
	    if (document.readyState === "complete") {
	        load_days(1,3);
	        for (var i = 1; i <= 3; i++) {
	        	document.getElementById("meals-" + i).className = 'display-meal-div';
	        }
	        clearInterval(readyStateCheckInterval);
	    }
	}, 1000);
	
	/*window.onbeforeunload = function (e) {
  		e = e || window.event;
	  	// For IE and Firefox prior to version 4
	  	if (e) {
	    	e.returnValue = 'All unsaved data will be lost! Do you really want to leave?';
	  	}
	  	// For others
	  	return 'All unsaved data will be lost! Do you really want to leave?';
	}*/
</script>
</html>